package com.xxxy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxy.mapper.CredentialsMapper;
import com.xxxy.pojo.Credentials;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private CredentialsMapper credentialsMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Credentials> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", username);
        Credentials credential = credentialsMapper.selectOne(queryWrapper);
        if (credential == null){
            String errorMsg = "user: "+username+" not be found";
            System.out.println(errorMsg);
            throw new UsernameNotFoundException(errorMsg);
        }
        List<GrantedAuthority> authorityList = Collections.singletonList((GrantedAuthority) () -> "USER");
        return new User(credential.getName(), credential.getPassword(), authorityList);
    }
}
